import { type FormInstance } from 'element-plus'
import { removeTrailingZeros } from '@/utils/common'
import Decimal from 'decimal.js'

interface Target {
  acceptor: string
  matter: string
  billAmount: string
  points: string
  open: number
}
/**
 * 处理表单提交核心逻辑
 * @param formEl 表单实例
 * @param type 业务类型 'discountList' | 'buy'
 * @param target 表单数据对象
 */
export const dealWith = async (formEl: FormInstance | undefined, type: string, target: Target) => {
  if (!formEl) return false

  return await formEl
    .validate()
    .then(() => {
      // 数值转换逻辑
      const points = new Decimal(target.points || 0).div(100)
      const billAmount = new Decimal(target.billAmount || 0).mul(10000)

      // 生成业务对象
      return {
        serialNumber: target[type + 'Len']++,
        matter: type === 'discountList' ? '贴现' : '买票',
        acceptor: target.acceptor,
        billAmount: target.billAmount,
        points: target.points,
        open: target.open,
        rebate:
          type !== 'discountList'
            ? removeTrailingZeros(points.mul(target.open).mul(billAmount))
            : '',
        interestDeduction:
          type === 'discountList'
            ? removeTrailingZeros(points.mul(target.open).mul(billAmount))
            : ''
      }
    })
    .catch((error) => {
      console.error('表单验证失败:', error)
      return null
    })
}

interface listsItem {
  serialNumber: number
  matter: string
  acceptor: string
  billAmount: string
  points: string
  open: number
  rebate: string
  interestDeduction: string
  checked?: boolean
}
/**
 * 处理表单编辑核心逻辑
 * @param type 业务类型 'discount' | 'buy'
 * @param target 表单数据对象
 * @param lists 表格数据对象
 * @return listsItem
 * @return string
 * */
export const dealWithEdit = async (type: string, target: Target, lists: listsItem) => {
  lists.acceptor = target.acceptor
  lists.billAmount = target.billAmount
  lists.points = target.points
  lists.open = target.open
  let points = new Decimal(target.points || 0)
  points = points.div(100)
  let billAmount = new Decimal(target.billAmount || 0)
  billAmount = billAmount.mul(10000)
  let newpoints = points.mul(target.open).mul(billAmount).toFixed(6).toString()
  newpoints = removeTrailingZeros(newpoints)
  const interestDeduction = type === 'discount' ? newpoints : ''
  const rebate = type === 'discount' ? '' : newpoints
  lists.interestDeduction = interestDeduction
  lists.rebate = rebate
  return lists
}

export const inputFormat = (field: string, target: Target) => {
  // const target = type === 'discount' ? discount : buy

  let value = target[field]
  // 正则表达式：允许数字和小数点
  value = value.replace(/[^0-9.]/g, '')

  // 确保只有一个小数点
  if (value.split('.').length > 2) {
    value = value.slice(0, -1)
  }

  // 更新目标对象的值
  target[field] = value
}
